home *** CD-ROM | disk | FTP | other *** search
- Path: ts1-026.jaxnet.com!user
- From: garyg@jax.jaxnet.com (Gary M. Greenberg)
- Newsgroups: comp.lang.c
- Subject: Re: [Q]How can I read ints and floats by using fgets() ?
- Date: Mon, 29 Jan 1996 23:51:33 -0500
- Organization: Southeast Network Services, Inc.
- Message-ID: <garyg-2901962351330001@ts1-026.jaxnet.com>
- References: <4e56sn$p6n@wraith.cc.uow.edu.au> <4e8i56$j4a@jaxnet.jaxnet.com>
- NNTP-Posting-Host: ts1-026.jaxnet.com
-
- Some guy, garyg@jax.jaxnet.com, wrote:
-
- > Abimanju Manoharan (am@wraith.cc.uow.edu.au) wrote:
- > : Hi everybody,
- > : I have a small problem in my c program. I want to read a file for exe.
- > : the file (file size is not constant):
- >
- > : 4 11
- > : 2.5 4 13 3.7
- > : 5 4 2.1
- > : 2.4
- >
- > : I have to read each line by using fgets(). then I have to convert this
- > : string. There are float values and int values are mixed.
- > : Du you any idea? or du you have another way to read this?
- >
- [snip ...]
-
- Don't know happened to that reply, but there was nuthin' in it
- worth anything. Oh well, let's try again ...
-
- This is different than my original answer, but I hope it illustrates how
- one might use fgets and scanf to determine the 'value' of input. This
- illustration takes input from stdin. Modifying it to use a file is trivial.
-
- Comments, criticism, and flames by post or email.
-
- /* fgets2scanf.c */
-
- #include <stdio.h>
- #include <string.h>
-
- #define LEN 256
-
- int main ()
- {
- char str[LEN], tmpstr[LEN];
- float fl;
- int i=0,j=0,pos=0,neg=0,not=0;
- printf("Enter a line: ");
- while(fgets(str,sizeof(str),stdin)!=NULL) {
- /*** chop newline && NULL terminate string ***/
- *(str+strlen(str)-1)='\0';
- i=0;
- while (i<=strlen(str)) {
- if((str[i])!=' ' && i<strlen(str)) {
- tmpstr[j]=str[i];
- j++;
- }
- if(str[i]==' '||str[i]=='\0'||i==strlen(str)) {
- tmpstr[j]='\0';
- j=0;
- if (sscanf(tmpstr,"%f",&fl)==1)
- (fl>=0.0)?pos++:neg++;
- else {
- not++;
- fflush(stdout);
- }
- }
- i++;
- }
- printf("Enter another line: ");
- }
- printf("Positive values: %d\n""Negative values: %d\n"
- "Discarded values: %d\n",pos,neg,not);
- return 0;
- }
- /*** end ***/
-
- gary /* the Sorcerer's Apprentice */
-
- "Why do we have to hide from the police, Daddy?"
- "Because we use vi, honey. They use emacs."
- "Unless we're on a Mac, then we use BBEdit 'cause `It Doesn't Suck!'"
-